package com.xuan.commons.shiro;

import com.xuan.commons.config.jwt.JwtConfig;
import com.xuan.commons.config.jwt.JwtToken;
import com.xuan.modules.system.entity.User;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.servlet.http.HttpServletRequest;

/**
 * @author renzhengxuan
 * @date 2021/5/21
 */
public class UserRealm extends AuthorizingRealm {

    /**
     * 必须重写此方法，不然shiro会报错
     * @param token
     * @return
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    /**
     * 认证
     * @param
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException {
        System.out.println("进入了认证方法");
        String token = (String) auth.getCredentials();
        if(token==null){
            throw new AuthenticationException("token为空");
        }
        User user = this.checkUserToken(token);
        return new SimpleAuthenticationInfo(user,token,getName());
    }

    /**
     *校验token的有效性
     * @param token
     * @return
     */
    private User checkUserToken(String token){
        String username = JwtConfig.getUsername(token);
        if(username == null){
            throw new AuthenticationException("token非法无效");
        }
        User user = new User();
        user.setUsername(username);
        return user;
    }
}
